import React, {useEffect, useState} from "react";
import {Input, Tree, TreeProps} from "antd";

import ProBox from "vendor/components/pro-box";
import ProAutoScrollbars from "vendor/components/pro-autoScrollbars";

import { useTreeData } from "./useTreeData";

interface OrgTreeProps extends TreeProps{
    onOrgChange?: (deptId: number) => void;
    isAllowCancelSelected?: boolean;    // 是否允许取消选中
}

const OrgTree: React.FC<OrgTreeProps> = ({onOrgChange, isAllowCancelSelected,...restProps}) => {
    const headerHeight = 32;
    const {loading, treeData, fetchOrgTreeData} = useTreeData();
    const [selectedDeptId, setSelectedDeptId] = useState<number>();

    useEffect(() => {
        if(treeData.length > 0){
            const deptId = treeData[0].key;
            setSelectedDeptId(deptId);
            onOrgChange && onOrgChange(deptId);
        }
    }, [treeData])

    return (
        <div style={{height: "100%", padding: 5}}>
            <Input.Search
                style={{height: headerHeight}}
                placeholder="请输入组织名称"
                onSearch={(value) => fetchOrgTreeData({deptName: value})}
                enterButton
                allowClear
            />

            <div style={{paddingTop: 8, height: `calc(100% - ${headerHeight}px)`}}>
                <ProBox loading={loading}>
                    <ProAutoScrollbars>
                        <Tree
                            // @ts-ignore
                            treeData={treeData}
                            defaultExpandedKeys={(treeData && treeData.length > 0) ? [treeData[0].key] : []}
                            selectedKeys={[selectedDeptId]}
                            selectable={true}
                            blockNode={true}
                            onSelect={(selectedKeys) => {
                                if(!isAllowCancelSelected && selectedKeys.length == 0) return;
                                const deptId = selectedKeys[0] as number;
                                setSelectedDeptId(deptId);
                                onOrgChange && onOrgChange(deptId);
                            }}
                            {...restProps}
                        />
                    </ProAutoScrollbars>
                </ProBox>
            </div>
        </div>
    )
}

OrgTree.defaultProps = {
    isAllowCancelSelected: true,
}

export default OrgTree;
